package band.wukong.practice.webservice.kh.sample04;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;

/**
 * 使用JAXB序列化、反序列化POJO
 *
 * @author wukong(wukonggg@139.com)
 */
public class JAXBSample {

    private static final Logger logger = LoggerFactory.getLogger(JAXBSample.class);

    public static void main(String[] args) throws JAXBException {
        marshal();
        unmarshal();
    }

    private static void marshal() throws JAXBException {
        Student stu = new Student(1, "左小祖咒", new Classroom(1, "肥猪流", 1999));

        JAXBContext ctx = JAXBContext.newInstance(Student.class);
        Marshaller marshaller = ctx.createMarshaller();
        marshaller.marshal(stu, System.out);
        System.out.println();
    }

    private static void unmarshal() throws JAXBException {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><student><classroom><grade>1999</grade><id>1</id><name>肥猪流</name></classroom><id>1</id><name>左小祖咒</name></student>";
        JAXBContext ctx = JAXBContext.newInstance(Student.class);
        Unmarshaller um = ctx.createUnmarshaller();
        Student stu = (Student) um.unmarshal(new StringReader(xml));
        logger.info(stu.toString());
    }



}
